﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace BoAddonBiz_FreightForwarder.Custom
{
    internal class QuarantineXml
    {
        public string CreateXml(string DocEntry, string Type)
        {
            try
            {
                string SQL = string.Empty;
                string CustomsDealaration = string.Empty;
                string TableName = string.Empty;
                XmlDocument xmlDoc_Quarantine = new XmlDocument();
                SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                xmlDoc_Quarantine.Load(System.Windows.Forms.Application.StartupPath + @"\Template\CustomsDeclaration.xml");
                TableName = Type == "I" ? "CTC" : "ATC";
                #region 报检单表头信息
                SQL = @"SELECT T8.U_PortCode U_BargainMethodCode,T3.AddId As CargoOwner
                        ,Case When ISNULL(T0.U_TransportCountryC,'') = '' Then (SELECT Code From DPA_empty..CountryOrigin Where Name = T0.U_TransportCountry ) Else T0.U_TransportCountryC End CountryCode
                        ,CASE When ISNULL(T0.U_LoadingPortCode,'') = '' Then (SELECT TOP 1 Code FROM DPA_empty..PortType Where Name = T0.U_LoadingPort) Else T0.U_LoadingPortCode End PortCode
                        ,CASE When '{1}' = 'I' Then T0.U_CollectingRate Else T0.U_SettleMethod End Collecting
                        ,t9.Code FCCurrency
                        ,t10.Code SafeCurrency
                        ,t11.Code OtherCurrency
                      ---
T0.U_CustomsDeclaration as EntryNO,--报关单号
T0.U_ApplyCustoms as DeclareToTheCustomsCode,--申报地海关代码
T0.U_InspectionType as InspectionCategory,--报检类别
T0.U_CusRegCode as BusinessUnitsCode,--经营单位编号
T0.U_DeliverRegCode as CIQBusinessUnitsCode,--报检经营单位代码  （收货人代码）
N'1105980157' as TheNotificationCode,--申报单位代码
N'北京海翔国际运输代理有限公司' as TheNotificationName,--申报单位名称
T0.U_InspectionNO as CIQTheNotificationCode,--报检企业注册号
T0.U_DeliverRegCode as ReceivingUnitCode,--收货单位代码
T0.U_DeliverName as ReceivingUnitName,--收货单位名称
T0.U_PayTaxCompany as TaxUnit,--纳税单位
 N''  ArriveCountriesCode,--启运国国别代码
 N'' CIQArriveCountriesCode,--保检启运国家代码
PortCode as ThePortOfDestinationCode,--装货港代码
N''  CIQThePortOfDestinationCode,--报检装货港代码
N'' as CIQInPortCode,--报检入境口岸代码
N'' as TheArrivalDate,--到货日期
N'' as GOODS_PLACE,--存货地点
T0.U_ModeOfTransport as MeansOfTransportMode,--运输方式
T0.U_Transportation as MeansOfTransportName,--运输工具名称
N'' as CIQMeansOfTransportMode,--报检运输工具代友码
T1.U_Flight as VoyageNO,--航次号
T0.U_WayBillNo as BillOfLadingNo,--提运单号
T0.U_ContractNo as ContractNo,--合同协议号
T0.U_TotalWeight as GrossWeight,--毛重
T0.U_TotalNetWeight as NetWeight,--净重
T0.U_PackageDescription as PackingType,--包装种类
T0.U_TotalNumber as Packages,--件数
T0.U_BargainMethodCode as TransactionMode,--成交方式
N'' as RegulatoryMode,--监管方式
U_Property as CutMode,--征免性质
U_DocumentType as EntryType --报关单类型

FROM [@AVA_FF_O{2}] T0
						INNER JOIN [@AVA_FF_OBNO] T1 ON T0.U_BaseEntry = T1.DocEntry
                        LEFT JOIN OCRD T3 ON T0.U_CardCode = T3.CardCode
                        LEFT JOIN [@AVA_FF_BAMD] T8 ON T0.U_BargainMethod = T8.Code
                        LEFT JOIN DPA_empty..CurrencyType t9 on t0.U_FCCurrency = t9.Symbol
                        LEFT JOIN DPA_empty..CurrencyType t10 on t0.U_SafeCurrency = t10.Symbol
                        LEFT JOIN DPA_empty..CurrencyType t11 on t0.U_OtherCurrency = t11.Symbol
                    Where T0.DocEntry = {0}";
                SQL = string.Format(SQL, DocEntry, Type, TableName);
                rs.DoQuery(SQL);
                if (rs.RecordCount > 0)
                {
                    CustomsDealaration = rs.Fields.Item("U_CustomsDeclaration").Value;

                    //CDXml.SelectSingleNode("//报关单表头信息/申报单位代码").InnerText = "1105980157";
                    //CDXml.SelectSingleNode("//报关单表头信息/申报单位名称").InnerText = "北京海翔国际运输代理有限公司";
                    //CDXml.SelectSingleNode("//报关单表头信息/录入单位代码").InnerText = "1105980157";
                    //CDXml.SelectSingleNode("//报关单表头信息/录入单位名称").InnerText = "北京海翔国际运输代理有限公司";

                    Object FieldValue = default(Object);
                    for (int i = 0; i < rs.Fields.Count; i++)
                    {
                        FieldValue = rs.Fields.Item(i).Value;
                        if (FieldValue.GetType() == typeof(String))
                        {
                            xmlDoc_Quarantine.SelectSingleNode("//" + rs.Fields.Item(i).Name).InnerText = FieldValue.ToString();
                        }
                        else if (FieldValue.GetType() == typeof(DateTime))
                        {
                            xmlDoc_Quarantine.SelectSingleNode("//" + rs.Fields.Item(i).Name).InnerText = ConvertDatetime((DateTime)FieldValue);
                        }
                    }

                }
                #endregion
                #region 报关单表体信息
                string customsDealarationLine = string.Empty;
                customsDealarationLine = xmlDoc_Quarantine.SelectSingleNode("//报关单表体信息").OuterXml;
                xmlDoc_Quarantine.SelectSingleNode("//报关单数据").RemoveChild(xmlDoc_Quarantine.SelectSingleNode("//报关单表体信息"));
                XmlDocument CDXmlLine = null;
                SQL = @"
                    SELECT 
T0.U_Origin as OriginCode,  -- 原产地
T0.U_Origin as CIQOriginCode,  -- 报检原产国代码
T0.U_ExemptionOfNature as DutyMode,  -- 征免方式
T0.U_HSCode as HsCode,  -- 商品编码
T0.U_ProductName as GoodsName,  -- 商品名称
T0.U_Norms as Model,  -- 规格型号
T0.U_Quantity as Quantity,  -- 成交数量
T0.U_Unit as QuantityUnit,  -- 成交单位
N'' as CIQQuantityUnit,  -- 报检成交单位代码
T0.U_Currency as Currency,  -- 币制
T0.U_Currency as CIQCurrency,  -- 报检货币单位代码
T0.U_Price as UnitPrice,  -- 成交单价
T0.U_Total as TotalPrice,  -- 成交总价
T0.U_Quantity as LegalQuantity,  -- 法定数量
T0.U_Unit as LegalUnit,  -- 法定单位
N'' as CIQLegalUnit,  -- 报检标准量单位代码
T0.U_Manufacturer as USE  -- 用途

--T0.U_CIQCode
--T0.U_WeightUnit
--T0.U_PackNum
--T0.U_HSQty
--T0.U_VerificationFile
--T0.U_PackItem
--T0.U_HSQtyUnit
--T0.U_GoodsWasteType
--T0.U_LicenseNo
--T0.U_ApproveNo
FROM [@AVA_FF_CTC1] T0 
                       
                    FROM [@AVA_FF_{0}1] t0
                        LEFT JOIN DPA_empty..CurrencyType t1 on t0.U_Currency = t1.Symbol
                    Where T0.DocEntry = {1}";
                rs.DoQuery(string.Format(SQL, TableName, DocEntry));
                string Standard = string.Empty, DeclareValue = string.Empty;
                for (int i = 0; i < rs.RecordCount; i++)
                {
                    CDXmlLine = new XmlDocument();
                    CDXmlLine.LoadXml(customsDealarationLine);
                    CDXmlLine.SelectSingleNode("//商品序号").InnerText = rs.Fields.Item("LineId").Value.ToString();
                    CDXmlLine.SelectSingleNode("//商品编码").InnerText = rs.Fields.Item("U_HSCode").Value.ToString();
                    CDXmlLine.SelectSingleNode("//货号").InnerText = rs.Fields.Item("U_ArticleNo").Value.ToString();
                    CDXmlLine.SelectSingleNode("//中文品名").InnerText = rs.Fields.Item("U_ProductName").Value.ToString();
                    CDXmlLine.SelectSingleNode("//英文品名").InnerText = rs.Fields.Item("U_ProducEName").Value.ToString();
                    CDXmlLine.SelectSingleNode("//规格型号").InnerText = DeclareValue;
                    CDXmlLine.SelectSingleNode("//备案序号").InnerText = rs.Fields.Item("U_RecordNo").Value.ToString();
                    CDXmlLine.SelectSingleNode("//成交数量").InnerText = ConvertNull(rs.Fields.Item("U_Quantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//成交单位").InnerText = rs.Fields.Item("ThirdUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//单价").InnerText = ConvertNull(rs.Fields.Item("U_Price").Value.ToString());
                    CDXmlLine.SelectSingleNode("//总价").InnerText = ConvertNull(rs.Fields.Item("U_Total").Value.ToString());
                    CDXmlLine.SelectSingleNode("//币制").InnerText = rs.Fields.Item("CurrencyCode").Value.ToString();
                    CDXmlLine.SelectSingleNode("//第一法定数量").InnerText = ConvertNull(rs.Fields.Item("U_FirstQuantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//第一法定单位").InnerText = rs.Fields.Item("FirstUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//第二法定数量").InnerText = ConvertNull(rs.Fields.Item("U_SecondQuantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//第二法定单位").InnerText = rs.Fields.Item("SecondUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//原产地").InnerText = rs.Fields.Item("U_Origin").Value.ToString();
                    CDXmlLine.SelectSingleNode("//用途或生产厂家").InnerText = rs.Fields.Item("U_Manufacturer").Value.ToString();
                    CDXmlLine.SelectSingleNode("//征免方式").InnerText = rs.Fields.Item("U_ExemptionOfNature").Value.ToString();
                    CDXmlLine.SelectSingleNode("//工缴费").InnerText = ConvertNull(rs.Fields.Item("U_Charges").Value.ToString());
                    CDXmlLine.SelectSingleNode("//版本号").InnerText = rs.Fields.Item("U_Version").Value.ToString();
                    CDXmlLine.SelectSingleNode("//归类标志").InnerText = rs.Fields.Item("U_Flag").Value.ToString();
                    CDXmlLine.SelectSingleNode("//备注").InnerText = rs.Fields.Item("U_Remarks").Value.ToString();

                    //CDXmlLine.SelectSingleNode("//提单号").InnerText = rs.Fields.Item("U_WayBillNo").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输方式").InnerText = rs.Fields.Item("U_ModeOfTransport").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具编号").InnerText = rs.Fields.Item("U_TransportationNo").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具名称").InnerText = rs.Fields.Item("U_Transportation").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具航次").InnerText = rs.Fields.Item("U_Voyage").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//实际进出境日期").InnerText = rs.Fields.Item("U_LeaveDate").Value.ToString();

                    XmlNode newnode = xmlDoc_Quarantine.SelectSingleNode("//报关单数据").OwnerDocument.ImportNode(CDXmlLine.LastChild, true);
                    xmlDoc_Quarantine.SelectSingleNode("//报关单数据").AppendChild(newnode);
                    rs.MoveNext();
                }
                string FreeTest = string.Empty;
                FreeTest = xmlDoc_Quarantine.SelectSingleNode("//报关单自由文本信息").OuterXml;
                xmlDoc_Quarantine.SelectSingleNode("//报关单数据").RemoveChild(xmlDoc_Quarantine.SelectSingleNode("//报关单自由文本信息"));
                CDXmlLine = new XmlDocument();
                CDXmlLine.LoadXml(FreeTest);
                XmlNode node = xmlDoc_Quarantine.SelectSingleNode("//报关单数据").OwnerDocument.ImportNode(CDXmlLine.LastChild, true);
                xmlDoc_Quarantine.SelectSingleNode("//报关单数据").AppendChild(node);
                #endregion
                string Platform = System.Configuration.ConfigurationManager.AppSettings["PlatformCode"];
                string Datetime = DateTime.Now.ToString("yyyyMMdd");
                string Number = DateTime.Now.ToString("HHmmssffff");// "0000000000".Substring(0, 10 - DocEntry.Length) + DocEntry.ToString();
                string TaskId = Platform + Datetime + Number;
                xmlDoc_Quarantine.SelectSingleNode("//企业配置信息/任务编号").InnerText = TaskId;
                xmlDoc_Quarantine.SelectSingleNode("//企业配置信息/企业编号").InnerText = TaskId;
                //保存                
                xmlDoc_Quarantine.Save(System.Configuration.ConfigurationManager.AppSettings["CustomsFilePath"] + @"\" + TaskId + ".xml");
                rs.DoQuery("UPDATE [@AVA_FF_O" + TableName + "] SET U_TaskNo='" + TaskId + "' Where DocEntry = " + DocEntry);
                return TaskId;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        private string ConvertNull(string Value)
        {
            if (Value == "0")
                return "";
            else
                return Value;
        }
        private string ConvertDatetime(DateTime Value)
        {
            if (Value.ToString("yyyy-MM-dd") == "1900-01-01")
                return "";
            else
                return Value.ToString("yyyy-MM-dd");
        }
    }
}
